package com.bdqn.zhao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.zhao.dao.IpParkimgMapper;
import com.bdqn.zhao.dao.IpParkMapper;
import com.bdqn.zhao.pojo.IpPark;
import com.bdqn.zhao.pojo.IpParkimg;
import com.bdqn.zhao.pojo.SysUser;
import com.bdqn.zhao.service.IpParkService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 园区表 服务实现类
 * </p>
 *
 * @author zhangsan
 * @since 2023-04-24
 */
@Service
public class IpParkServiceImpl extends ServiceImpl<IpParkMapper, IpPark> implements IpParkService {

    @Autowired
    private IpParkMapper ipParkMapper;

    @Autowired
    private IpParkimgMapper ipParkImgMapper;


    LocalDate date = LocalDate.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    //全查询园区表信息
    @Override
    public List<IpPark> selectAllipPark(HttpSession session) {

        // 1。全查类别
        Page<IpPark> page = new Page<>(1, 3);//设置分页参数
        IPage<IpPark> parkIPage = ipParkMapper.selectPage(page, new QueryWrapper<>());
        List<IpPark> ipParks1 = parkIPage.getRecords();//查询到的分页数据
        session.setAttribute("ipParkList", ipParks1);
        session.setAttribute("ipParkCount", ipParks1.size());

        //当前页数
        session.setAttribute("current", page.getCurrent());
        session.setAttribute("pages", page.getPages());
        return ipParks1;
    }

    @Override
    public String selectAllipParks(HttpSession session) {
        List<IpPark> list = list();
        session.setAttribute("ippark", list);
        return "true";
    }

    // 园区列表 --条件查询 --上下页分页
    @Override
    public Map<String, Object> selectOneipPark(int index, int count, String parkName) {

        Map<String, Object> map = new HashMap<>();

        List<IpPark> ipParks = new ArrayList<>();
        Page<IpPark> page = new Page<>(index, count);//设置分页参数
        QueryWrapper<IpPark> ipParkQueryWrapper = new QueryWrapper<>();
        if (parkName != "" && parkName != null) {
            ipParkQueryWrapper.like("park_name", parkName);
            ipParks = ipParkMapper.selectList(ipParkQueryWrapper);
        }
        IPage<IpPark> ipParkIPage = ipParkMapper.selectPage(page, ipParkQueryWrapper);
        List<IpPark> ipParks1 = ipParkIPage.getRecords();//查询到的分页数据

        map.put("ipParkList", ipParks1);
        map.put("ipParkCount", ipParks.size());  // 赋值总共的记录数

        map.put("current", page.getCurrent());  //当前页数
        map.put("pages", page.getPages()); // 总页数
        return map;
    }


    // 园区列表 -- 修改园区上下架状态
    @Override
    public Map<String, Object> updateStatus(int parkid, int status) {
        HashMap<String, Object> map = new HashMap<>();
        UpdateWrapper<IpPark> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("park_id", parkid);
        ipParkMapper.update(new IpPark(status), updateWrapper);
        map.put("success", true);
        return map;
    }

    // 园区列表 -- 新增园区信息
    @Override
    public Boolean addIpPark(IpPark ipPark,
                             List<String> ipParkSingleImageList,
                             List<String> ipParkImageList,
                             Map hasaMap,
                             HttpSession session) {

        SysUser sysUser = (SysUser) session.getAttribute("User");
        ipParkSingleImageList = (ArrayList) hasaMap.get("ipParkSingleImageList");
        ipParkImageList = (ArrayList) hasaMap.get("ipParkImageList");
        // 1.新增园区信息表
//        ipPark.setCreateBy(sysUser.getUserName());
        ipPark.setCreateBy("dong");
        ipPark.setCreateTime(Date.valueOf(date.format(formatter)));
        boolean isSuccess = save(ipPark);

        // 返回主键ID
        System.out.println("主键 ID: " + ipPark.getParkId());

        //2.新增 园区 图片 地址
        // 新增小图
        if (ipParkSingleImageList.size() != 0 && ipParkSingleImageList != null) {
            for (int i = 0; i < ipParkSingleImageList.size(); i++) {
                String image = ipParkSingleImageList.get(i).substring(ipParkSingleImageList.get(i).lastIndexOf("/") + 1);
                ipParkImgMapper.insert(new IpParkimg().setParkimgSrc(image).setParkimgType(0).setParkId(ipPark.getParkId()).setCreateBy("栋").setCreateTime(Date.valueOf(date.format(formatter))));
            }
        }

        //新增 园区 图片 地址
        // 新增 banner图
        if (ipParkImageList != null && ipParkImageList.size() != 0) {
            for (int i = 0; i < ipParkImageList.size(); i++) {
                String image = ipParkImageList.get(i).substring(ipParkImageList.get(i).lastIndexOf("/") + 1);
                ipParkImgMapper.insert(new IpParkimg().setParkimgSrc(image).setParkimgType(0).setParkId(ipPark.getParkId()));
            }
        }

        return isSuccess;
    }

    @Override
    public Map<String, Object> uploadProductImage(MultipartFile alogoPicPath, int parkimgType, HttpSession session) {

        // parkimgType 获取上传图片的属性 0 是小图  1 是banner图

        HashMap<String, Object> map = new HashMap<>();
        String path = session.getServletContext().getRealPath("/res/images/item/productSinglePicture");
        if (parkimgType == 0) {
            Long size = alogoPicPath.getSize();
            //获取原始文件名
            String filename = alogoPicPath.getOriginalFilename();
            assert filename != null;
            //获取文件后缀
            String suffix = FilenameUtils.getExtension(filename);
            if (size > 5242800) {
                map.put("uploadFileError", "文件大小不能超过5242800kb");
                map.put("success", false);
                return map;
            } else if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("pneg")) {
                //文件存储地址
                UUID uuid = UUID.randomUUID();
                String newName = uuid + "." + suffix;
                File file = new File(path);
                if (!file.exists()) {
                    boolean mkdir = file.mkdir();
                }
                try {
                    //进行拷贝上传操作  将左边拷贝到右边的地址
                    alogoPicPath.transferTo(new File(file, newName));
                } catch (IOException e) {
                    e.printStackTrace();
                    map.put("uploadFileError", "文件上传失败");
                    map.put("success", false);
                    return map;
                }
                map.put("success", true);
                map.put("fileName", newName);
                return map;

            } else {
                map.put("uploadFileError", "文件类型问题");
                map.put("success", false);
                return map;
            }
        }
        path = session.getServletContext().getRealPath("/res/images/item/productDetailsPicture");
        //详细图片
        if (parkimgType == 1) {
            Long size = alogoPicPath.getSize();
            //获取原始文件名
            String filename = alogoPicPath.getOriginalFilename();
            assert filename != null;
            //获取文件后缀
            String suffix = FilenameUtils.getExtension(filename);
            if (size > 5242800) {
                map.put("uploadFileError", "文件大小不能超过5242800kb");
                map.put("success", false);
                return map;
            } else if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("pneg")) {
                //文件存储地址
                UUID uuid = UUID.randomUUID();
                String newName = uuid + "." + suffix;
                File file = new File(path);
                if (!file.exists()) {
                    boolean mkdir = file.mkdir();
                }
                try {
                    alogoPicPath.transferTo(new File(path, newName));
                } catch (Exception e) {
                    map.put("uploadFileError", "文件上传失败");
                    map.put("success", false);
                    return map;
                }
                map.put("success", true);
                map.put("fileName", newName);
                return map;
            } else {
                map.put("uploadFileError", "文件类型问题");
                map.put("success", false);
                return map;
            }
        }

        return map;
    }

    @Override
    public int updateipPark(int pid, HttpSession session) {
        IpPark ipPark = getById(pid);
        // 查询出园区的图片地址
        QueryWrapper<IpParkimg> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("park_id", pid);
        ipPark.setIpParkimgList(ipParkImgMapper.selectList(objectQueryWrapper));
        session.setAttribute("ipPark", ipPark);
        return ipPark.getPid();
    }


    @Override
    public Map<String, Object> updates(int pid, IpPark ipPark,
                                      List<String> ipParkSingleImageList,
                                      List<String> ipParkImageList,
                                      Map hasaMap, HttpSession session) {

        HashMap<String, Object> map = new HashMap();
        SysUser sysUser = (SysUser) session.getAttribute("User");
        ipParkSingleImageList = (ArrayList) hasaMap.get("ipParkSingleImageList");
        ipParkImageList = (ArrayList) hasaMap.get("ipParkImageList");
        // 1.修改园区信息表
//        ipPark.setCreateBy(sysUser.getUserName());
        ipPark.setUpdateBy("dong");
        ipPark.setUpdateTime(Date.valueOf(date.format(formatter)));
        UpdateWrapper<IpPark> updateWrapper2 = new UpdateWrapper();
        updateWrapper2.eq("park_id", pid);
        boolean isSuccess = update(ipPark,updateWrapper2);

        // 返回主键ID
        System.out.println("主键 ID: " + ipPark.getParkId());

        //2.新增 园区 图片 地址
        // 新增小图
        if (ipParkSingleImageList.size() != 0 && ipParkSingleImageList != null) {
            for (int i = 0; i < ipParkSingleImageList.size(); i++) {
                String image = ipParkSingleImageList.get(i).substring(ipParkSingleImageList.get(i).lastIndexOf("/") + 1);
                ipParkImgMapper.insert(new IpParkimg().setParkimgSrc(image).setParkimgType(0).setParkId(pid).setCreateBy("栋").setCreateTime(Date.valueOf(date.format(formatter))));
            }
        }

        //新增 园区 图片 地址
        // 新增 banner图
        if (ipParkImageList != null && ipParkImageList.size() != 0) {
            for (int i = 0; i < ipParkImageList.size(); i++) {
                String image = ipParkImageList.get(i).substring(ipParkImageList.get(i).lastIndexOf("/") + 1);
                ipParkImgMapper.insert(new IpParkimg().setParkimgSrc(image).setParkimgType(0).setParkId(pid));
            }
        }
        map.put("success", true);
        return map;

    }
}
